//
//  ShowMapViewController.m
//  WZEfengAndEtong
//
//  Created by 李旭 on 16/8/16.
//  Copyright © 2016年 wanzhao. All rights reserved.
//

#import "ShowMapViewController.h"
#import <BaiduMapAPI_Map/BMKMapView.h>
#import <BaiduMapAPI_Map/BMKPolyline.h>
#import <BaiduMapAPI_Map/BMKPolylineView.h>
#import <BaiduMapAPI_Map/BMKPointAnnotation.h>
#import <BaiduMapAPI_Location/BMKLocationService.h>
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import "Masonry.h"
#import <BaiduMapAPI_Search/BMKGeocodeSearch.h>
#import <BaiduMapAPI_Search/BMKRouteSearch.h>
#import <BaiduMapAPI_Search/BMKGeocodeSearchOption.h>
#import "MBProgressHUD.h"
@interface ShowMapViewController ()<BMKGeoCodeSearchDelegate,BMKLocationServiceDelegate,BMKMapViewDelegate,BMKRouteSearchDelegate>
@property (nonatomic,strong) BMKMapView *mapView;
@property (nonatomic,strong) BMKGeoCodeSearch *search;
@property (nonatomic,strong) BMKRouteSearch *driveSearch;
@property (nonatomic,copy) NSString *mylocationName;
@property (nonatomic,strong) BMKLocationService *service;
@end

@implementation ShowMapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configMap];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    BMKReverseGeoCodeOption *option = [[BMKReverseGeoCodeOption alloc]init];
    option.reverseGeoPoint = _location.coordinate;
    [_search reverseGeoCode:option];
}
-(void)addAnnotation:(CLLocation*)userlocation
{
    BMKPointAnnotation *annotation = [BMKPointAnnotation new];
    annotation.title =  _mylocationName;
    annotation.coordinate = userlocation.coordinate;
    [self.mapView addAnnotation:annotation];
   [_mapView setCenterCoordinate:_location.coordinate animated:YES];

}
-(void)configMap
{
    _mapView = [[BMKMapView alloc]init];
     self.mapView.zoomLevel = 18;
    _mapView.delegate = self;
    [self.view addSubview:_mapView];
    [_mapView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_equalTo(0);
    }];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage:[UIImage imageNamed:@"backtobegin"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(backToBegin) forControlEvents:UIControlEventTouchUpInside];
    [_mapView addSubview:button];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-20);
        make.top.mas_equalTo(20);
        make.width.height.mas_equalTo(30);
    }];
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
    [button1 setBackgroundImage:[UIImage imageNamed:@"weizhi"] forState:UIControlStateNormal];
    [button1 addTarget:self action:@selector(beginServer) forControlEvents:UIControlEventTouchUpInside];
    [_mapView addSubview:button1];
    [button1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-20);
        make.bottom.mas_offset(-100);
        make.width.height.mas_equalTo(30);
    }];
    _search = [[BMKGeoCodeSearch alloc]init];
    _search.delegate = self;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)dealloc
{
    _driveSearch.delegate = nil;
    _search.delegate = nil;
    _service.delegate = nil;
    _mapView.delegate = nil;
    if (_mapView) {
        _mapView = nil;
    }
}
-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    self.mylocationName = result.address;
    [self addAnnotation:_location];
    [self addinfomationView];
}
-(void)addinfomationView
{
    UILabel *lable = [[UILabel alloc]init];
    lable.backgroundColor = [UIColor whiteColor];
    lable.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:20];
    lable.textAlignment = NSTextAlignmentCenter;
    lable.numberOfLines = 0 ;
    lable.text = self.mylocationName;
    [self.mapView addSubview:lable];
    [lable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo(80);
    }];
}
-(void)backToBegin
{
    [_mapView setCenterCoordinate:_location.coordinate animated:YES];
}
-(void)beginServer
{
    _service = [[BMKLocationService alloc]init];
    _service.delegate = self;
    _driveSearch = [[BMKRouteSearch alloc]init];
    _driveSearch.delegate = self;
    [_service startUserLocationService];
   

}
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    [_service stopUserLocationService];
  
    BMKPointAnnotation *annotation = [BMKPointAnnotation new];
    annotation.title =  @"我";
    annotation.coordinate = userLocation.location.coordinate;
    [self.mapView addAnnotation:annotation];
    [self getOverlayPointWithFriendLocation:userLocation.location AndMyLocation:_location];
    
}
-(void)getOverlayPointWithFriendLocation:(CLLocation*)friendLocation AndMyLocation:(CLLocation*)myLocation;
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.mapView animated:YES];
    hud.labelText = @"正在获取行车线路...";
    BMKPlanNode *startNode = [[BMKPlanNode alloc]init];
    CLLocationCoordinate2D startCoordinate;
    startCoordinate.latitude =friendLocation.coordinate.latitude;
    startCoordinate.longitude =friendLocation.coordinate.longitude;
    startNode.pt = startCoordinate;
    BMKPlanNode *endNode = [[BMKPlanNode alloc]init];
    CLLocationCoordinate2D endCoordnate;
    endCoordnate.latitude = myLocation.coordinate.latitude;
    endCoordnate.longitude = myLocation.coordinate.longitude;
    endNode.pt = endCoordnate;
    BMKDrivingRoutePlanOption * drivingRoutePlanOption = [[BMKDrivingRoutePlanOption alloc]init];
    drivingRoutePlanOption.from = startNode;
    drivingRoutePlanOption.to = endNode;
    [_driveSearch drivingSearch:drivingRoutePlanOption];
    BMKCoordinateRegion region ;
    CLLocationDegrees latitude;
    CLLocationDegrees longitude;
    BMKCoordinateSpan span;
    if (myLocation.coordinate.latitude > friendLocation.coordinate.latitude) {
        latitude =myLocation.coordinate.latitude -(myLocation.coordinate.latitude - friendLocation.coordinate.latitude)/2.0;
        span.latitudeDelta = myLocation.coordinate.latitude - friendLocation.coordinate.latitude;
    }
    else
    {
        latitude =friendLocation.coordinate.latitude -(friendLocation.coordinate.latitude - myLocation.coordinate.latitude)/2.0;
        span.latitudeDelta = friendLocation.coordinate.latitude - myLocation.coordinate.latitude;
    }
    if (myLocation.coordinate.longitude > friendLocation.coordinate.longitude) {
        longitude = myLocation.coordinate.longitude - (myLocation.coordinate.longitude - friendLocation.coordinate.longitude)/2.0;
        span.longitudeDelta = myLocation.coordinate.longitude - friendLocation.coordinate.longitude;
    }
    else
    {
        longitude = friendLocation.coordinate.longitude - (friendLocation.coordinate.longitude - myLocation.coordinate.longitude)/2.0;
        span.longitudeDelta = friendLocation.coordinate.longitude - myLocation.coordinate.longitude;
    }
    region.center = CLLocationCoordinate2DMake(latitude, longitude);
    region.span = span;
    [_mapView setRegion:region];
    [_mapView setZoomLevel:_mapView.zoomLevel-1];
}
//查找路线回调
-(void)onGetDrivingRouteResult:(BMKRouteSearch *)searcher result:(BMKDrivingRouteResult *)result errorCode:(BMKSearchErrorCode)error
{
    
    if (error == BMK_SEARCH_NO_ERROR) {
       BMKDrivingRouteLine* plan = (BMKDrivingRouteLine*)[result.routes objectAtIndex:0];
        NSInteger size = [plan.steps count];
        NSInteger planPointCounts = 0;
        for (int i = 0; i < size; i++) {
            BMKDrivingStep* transitStep = [plan.steps objectAtIndex:i];
            planPointCounts += transitStep.pointsCount;
        }
        BMKMapPoint *temppoints = new BMKMapPoint[planPointCounts];
        int i = 0;
        for (int j = 0; j < size; j++) {
            BMKDrivingStep* transitStep = [plan.steps objectAtIndex:j];
            int k=0;
            for(k=0;k<transitStep.pointsCount;k++) {
                temppoints[i].x = transitStep.points[k].x;
                temppoints[i].y = transitStep.points[k].y;
                i++;
            }
            
        }
        BMKPolyline* polyLine = [BMKPolyline polylineWithPoints:temppoints count:planPointCounts];
        [_mapView addOverlay:polyLine];
        [MBProgressHUD hideHUDForView:_mapView];
        
    }
}
- (BMKOverlayView *)mapView:(BMKMapView *)mapView viewForOverlay:(id <BMKOverlay>)overlay{
    if ([overlay isKindOfClass:[BMKPolyline class]]){
        BMKPolylineView* polylineView = [[BMKPolylineView alloc]initWithOverlay:overlay];
        polylineView.strokeColor = WZRGBColor(86, 154, 252);
        polylineView.lineWidth = 5.0;
        return polylineView;
    }
    return nil;
}
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[BMKPointAnnotation class]]) {
        BMKPinAnnotationView *newAnnotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"myAnnotation"];
        newAnnotationView.pinColor = BMKPinAnnotationColorRed;
        newAnnotationView.animatesDrop = YES;
        newAnnotationView.draggable = NO;
        return newAnnotationView;
    }
    return nil;
}
@end
